
import 'package:flustars/flustars.dart';

import 'Interceptor.dart';
import 'LoginInterceptor.dart';

class LoginInterceptChain {

  int index = 0;
  List<Interceptor> _interceptors = [];
  late LoginInterceptor _loginIntercept;

  //私有构造函数
  LoginInterceptChain._(){
    // 默认初始化Login的拦截器
    _loginIntercept = LoginInterceptor();
  }
  // 单例实例
  static final LoginInterceptChain _instance = LoginInterceptChain._();
  // 获取单例实例
  factory LoginInterceptChain() => _instance;

  //执行拦截器
  void process(){
    if(_interceptors.isEmpty) return;
    if(index < _interceptors.length) {
      Interceptor interceptor = _interceptors[index];
      index++;
      interceptor.interceptor(this);
    }else if(index == _interceptors.length){
      clearAllInterceptors();
    }
  }

  // 添加默认的再执行拦截器
  LoginInterceptChain addInterceptor(Interceptor interceptor){
      // 默认添加Login判断的拦截器
    if(!_interceptors.contains(_loginIntercept)){
      _interceptors.add(_loginIntercept);
    }
    if(!_interceptors.contains(interceptor)) {
      _interceptors.add(interceptor);
    }
    return this;
  }

  // 放行登录判断拦截器
  void loginFinished() {
    if (_interceptors.contains(_loginIntercept) && _interceptors.length > 1) {
      _loginIntercept.loginFinished();
    }
  }

  static bool isLogin(){
    return SpUtil.getString('token',defValue: "")?.isNotEmpty??false;
  }

  void clearAllInterceptors() {
    index = 0;
    _interceptors.clear();
  }

}

